import axios from 'axios'
import {
  ElMessage
} from 'element-plus'

const instance = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 10000,
})

instance.defaults.headers.post['Content-Type'] = 'application/json'


/** 添加请求拦截器 **/
instance.interceptors.request.use(config => {
  if (config.method === 'get') { // 添加时间戳参数，防止浏览器（IE）对get请求的缓存
    config.params = {
      ...config.params,
      t: new Date().getTime()
    }
  }
  return config
}, error => {
  return Promise.reject(error)
})

/** 添加响应拦截器  **/
instance.interceptors.response.use(response => {
  if (response.status === 200) {
    return Promise.resolve(response.data)
  } else {
    return Promise.reject(response.data)
  }
}, error => {
  console.log('error:', error)
  if (error && error.response && error.response.status) {
    switch (error.response.status) {
      //请求参数不正确
      case 400:
        ElMessage.error(`请求参数错误:${error.response.data.data}`)
        break;
      // 404请求不存在
      case 404:
        ElMessage.error('网络请求不存在!');
        break;
      // 其他错误，直接抛出错误提示
      default:
        ElMessage.error(error.response.data.message);
    }
    return Promise.reject(error.response);
  } else {
    ElMessage.error(error);
    return Promise.reject(error)
  }
})

/* 统一封装get请求 */
export const get = (url, params, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'get',
      url,
      params,
      ...config
    }).then(response => {
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}

/* 统一封装post请求  */
export const post = (url, data, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'post',
      url,
      data,
      ...config
    }).then(response => {
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}
